<template>
  <div class="message-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="sidebar-card">
          <div class="folder-list">
            <div
              class="folder-item"
              :class="{ active: activeFolder === 'inbox' }"
              @click="switchFolder('inbox')"
            >
              <i class="el-icon-message"></i>
              <span>收件箱</span>
              <el-badge :value="messageCount.inbox" :max="99" v-if="messageCount.inbox > 0" />
            </div>
            <div
              class="folder-item"
              :class="{ active: activeFolder === 'sendbox' }"
              @click="switchFolder('sendbox')"
            >
              <i class="el-icon-position"></i>
              <span>发件箱</span>
              <el-badge :value="messageCount.sendbox" :max="99" v-if="messageCount.sendbox > 0" />
            </div>
            <div
              class="folder-item"
              :class="{ active: activeFolder === 'draft' }"
              @click="switchFolder('draft')"
            >
              <i class="el-icon-document"></i>
              <span>草稿箱</span>
              <el-badge :value="messageCount.draft" :max="99" v-if="messageCount.draft > 0" />
            </div>
            <div
              class="folder-item"
              :class="{ active: activeFolder === 'star' }"
              @click="switchFolder('star')"
            >
              <i class="el-icon-star-off"></i>
              <span>星标邮件</span>
              <el-badge :value="messageCount.star" :max="99" v-if="messageCount.star > 0" />
            </div>
            <div
              class="folder-item"
              :class="{ active: activeFolder === 'rubbish' }"
              @click="switchFolder('rubbish')"
            >
              <i class="el-icon-delete"></i>
              <span>垃圾箱</span>
              <el-badge :value="messageCount.rubbish" :max="99" v-if="messageCount.rubbish > 0" />
            </div>
          </div>

          <el-button type="primary" @click="handleCompose" class="compose-btn">
            <i class="el-icon-edit"></i>
            <span>写信</span>
          </el-button>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card class="message-card">
          <div class="message-header">
            <div class="header-title">{{ folderTitles[activeFolder] }}</div>
            <div class="header-actions">
              <el-input
                v-model="searchKeywords"
                placeholder="搜索邮件"
                clearable
                @keyup.enter="handleSearch"
                style="width: 200px; margin-right: 10px"
              >
                <template #append>
                  <el-button icon="el-icon-search" @click="handleSearch"></el-button>
                </template>
              </el-input>
              <el-button @click="handleRefresh">刷新</el-button>
            </div>
          </div>

          <div class="message-toolbar" v-if="activeFolder !== 'rubbish'">
            <el-checkbox v-model="selectAll" @change="handleSelectAll"></el-checkbox>
            <el-dropdown @command="handleBatchAction">
              <el-button>
                批量操作
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete" v-if="activeFolder !== 'rubbish'">
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item command="star" v-if="activeFolder === 'inbox'">
                    标星
                  </el-dropdown-item>
                  <el-dropdown-item command="unstar" v-if="activeFolder === 'star'">
                    取消标星
                  </el-dropdown-item>
                  <el-dropdown-item command="recovery" v-if="activeFolder === 'rubbish'">
                    恢复
                  </el-dropdown-item>
                  <el-dropdown-item command="clear" v-if="activeFolder === 'rubbish'">
                    彻底删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <el-table
            :data="messageList"
            border
            v-loading="loading"
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="from_name"
              label="发件人"
              width="150"
              v-if="activeFolder === 'inbox'"
            >
              <template #default="scope">
                {{ scope.row.from_name || '系统消息' }}
              </template>
            </el-table-column>
            <el-table-column prop="title" label="主题" min-width="200">
              <template #default="scope">
                <el-link @click="handleViewMessage(scope.row)" :underline="false">
                  {{ scope.row.title }}
                </el-link>
                <el-tag
                  v-if="scope.row.is_star === 1"
                  type="warning"
                  effect="dark"
                  size="small"
                  style="margin-left: 10px"
                >
                  星标
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="send_time" label="时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.send_time) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handleViewMessage(scope.row)"
                  v-if="activeFolder !== 'sendbox' && activeFolder !== 'draft'"
                >
                  查看
                </el-button>
                <el-button
                  size="small"
                  @click="handleEditMessage(scope.row)"
                  v-if="activeFolder === 'draft'"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  @click="handleSendMessage(scope.row)"
                  v-if="activeFolder === 'draft'"
                >
                  发送
                </el-button>
                <el-dropdown @command="handleMessageAction">
                  <el-button size="small">
                    更多
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        :command="{ action: 'delete', row: scope.row }"
                        v-if="activeFolder !== 'rubbish'"
                      >
                        删除
                      </el-dropdown-item>
                      <el-dropdown-item
                        :command="{ action: 'star', row: scope.row }"
                        v-if="activeFolder === 'inbox' && scope.row.is_star !== 1"
                      >
                        标星
                      </el-dropdown-item>
                      <el-dropdown-item
                        :command="{ action: 'unstar', row: scope.row }"
                        v-if="activeFolder === 'inbox' && scope.row.is_star === 1"
                      >
                        取消标星
                      </el-dropdown-item>
                      <el-dropdown-item
                        :command="{ action: 'recovery', row: scope.row }"
                        v-if="activeFolder === 'rubbish'"
                      >
                        恢复
                      </el-dropdown-item>
                      <el-dropdown-item
                        :command="{ action: 'clear', row: scope.row }"
                        v-if="activeFolder === 'rubbish'"
                      >
                        彻底删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="queryForm.page"
              v-model:page-size="queryForm.limit"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 写信对话框 -->
    <el-dialog v-model="composeDialogVisible" :title="composeDialogTitle" width="60%">
      <el-form :model="messageForm" :rules="messageRules" ref="messageFormRef" label-width="80px">
        <el-form-item label="收件人" prop="uids">
          <el-select
            v-model="messageForm.uids"
            multiple
            placeholder="请选择收件人"
            style="width: 100%"
          >
            <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题" prop="title">
          <el-input v-model="messageForm.title" placeholder="请输入邮件主题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入邮件内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="/upload"
            multiple
            :file-list="fileList"
            :on-success="handleUploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="composeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveDraft">保存草稿</el-button>
          <el-button type="success" @click="handleSendMessage">发送</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看消息对话框 -->
    <el-dialog v-model="viewDialogVisible" :title="viewMessageTitle" width="60%">
      <div v-if="currentMessage">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="发件人">
            {{ currentMessage.from_name || '系统消息' }}
          </el-descriptions-item>
          <el-descriptions-item label="主题">{{ currentMessage.title }}</el-descriptions-item>
          <el-descriptions-item label="时间">
            {{ formatTime(currentMessage.send_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="内容">
            <div v-html="currentMessage.content"></div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useHomeStore } from '../../store/home'
  import { ElMessage } from 'element-plus'

  const homeStore = useHomeStore()

  // 当前活动文件夹
  const activeFolder = ref('inbox')

  // 文件夹标题映射
  const folderTitles: Record<string, string> = {
    inbox: '收件箱',
    sendbox: '发件箱',
    draft: '草稿箱',
    star: '星标邮件',
    rubbish: '垃圾箱',
  }

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
    read: '',
    types: '',
  })

  // 消息表单
  const messageForm = reactive({
    id: 0,
    uids: [],
    title: '',
    content: '',
    file_ids: '',
    is_draft: 2, // 1-发送 2-草稿
  })

  // 表单验证规则
  const messageRules = {
    uids: [{ required: true, message: '请选择收件人', trigger: 'change' }],
    title: [{ required: true, message: '请输入邮件主题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入邮件内容', trigger: 'blur' }],
  }

  // 数据相关
  const messageList = ref<any[]>([])
  const total = ref(0)
  const loading = ref(false)
  const messageCount = ref({
    inbox: 0,
    sendbox: 0,
    draft: 0,
    star: 0,
    rubbish: 0,
  })

  // 对话框相关
  const composeDialogVisible = ref(false)
  const composeDialogTitle = ref('写信')
  const viewDialogVisible = ref(false)
  const viewMessageTitle = ref('查看消息')
  const currentMessage = ref<any>(null)

  // 表单引用
  const messageFormRef = ref()
  const searchKeywords = ref('')

  // 选中项
  const selectedMessages = ref<any[]>([])
  const selectAll = ref(false)

  // 用户列表和文件列表
  const users = ref<{ id: number; name: string }[]>([])
  const fileList = ref([])

  // 计算属性 - 当前列表数据
  // const currentList = computed(() => {
  //   switch (activeFolder.value) {
  //     case 'inbox':
  //       return homeStore.msgs
  //     case 'sendbox':
  //     case 'draft':
  //       return homeStore.messages
  //     case 'star':
  //       return homeStore.msgs
  //     case 'rubbish':
  //       return homeStore.msgs
  //     default:
  //       return []
  //   }
  // })

  // 切换文件夹
  const switchFolder = (folder: string) => {
    activeFolder.value = folder
    queryForm.page = 1
    loadMessageList()
  }

  // 加载消息列表
  const loadMessageList = async () => {
    loading.value = true
    try {
      let res
      switch (activeFolder.value) {
        case 'inbox':
          res = await homeStore.getInboxListAction(queryForm)
          break
        case 'sendbox':
          res = await homeStore.getSendboxListAction(queryForm)
          break
        case 'draft':
          res = await homeStore.getDraftListAction(queryForm)
          break
        case 'star':
          res = await homeStore.getStarListAction(queryForm)
          break
        case 'rubbish':
          res = await homeStore.getRubbishListAction(queryForm)
          break
      }

      if (res && res.code === 0) {
        messageList.value = res.data
        total.value = res.count
      } else {
        ElMessage.error((res && res.msg) || '获取消息列表失败')
      }
    } catch (error) {
      ElMessage.error('获取消息列表失败')
    } finally {
      loading.value = false
    }
  }

  // 加载消息统计
  const loadMessageCount = async () => {
    try {
      const res = await homeStore.getUnreadStatisticsAction()
      if (res.code === 0) {
        messageCount.value = res.data as any
      }
    } catch (error) {
      // 静默处理错误
    }
  }

  // 搜索
  const handleSearch = () => {
    queryForm.keywords = searchKeywords.value
    queryForm.page = 1
    loadMessageList()
  }

  // 刷新
  const handleRefresh = () => {
    loadMessageList()
    loadMessageCount()
  }

  // 写信
  const handleCompose = () => {
    composeDialogTitle.value = '写信'
    Object.assign(messageForm, {
      id: 0,
      uids: [],
      title: '',
      content: '',
      file_ids: '',
      is_draft: 2,
    })
    composeDialogVisible.value = true
  }

  // 查看消息
  const handleViewMessage = async (row: any) => {
    try {
      let res
      if (activeFolder.value === 'sendbox' || activeFolder.value === 'draft') {
        res = await homeStore.viewMessageAction(row.id)
      } else {
        res = await homeStore.readMsgAction(row.id)
      }

      if (res.code === 0) {
        currentMessage.value = res.data
        viewMessageTitle.value = res.data.title
        viewDialogVisible.value = true
      } else {
        ElMessage.error(res.msg || '查看消息失败')
      }
    } catch (error) {
      ElMessage.error('查看消息失败')
    }
  }

  // 编辑消息
  const handleEditMessage = (row: any) => {
    composeDialogTitle.value = '编辑草稿'
    Object.assign(messageForm, row)
    composeDialogVisible.value = true
  }

  // 保存草稿
  const handleSaveDraft = () => {
    messageFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const formData = { ...messageForm, is_draft: 2 }
          const res: any = await homeStore.saveMessageAction(formData)
          if (res && res.code === 0) {
            ElMessage.success('保存草稿成功')
            composeDialogVisible.value = false
            loadMessageList()
          } else {
            ElMessage.error((res && res.msg) || '保存草稿失败')
          }
        } catch (error) {
          ElMessage.error('保存草稿失败')
        }
      }
    })
  }

  // 发送消息
  const handleSendMessage = async (row?: any) => {
    if (row) {
      // 从草稿箱发送
      try {
        const res: any = await homeStore.sendMessageAction(row.id)
        if (res && res.code === 0) {
          ElMessage.success('发送成功')
          loadMessageList()
        } else {
          ElMessage.error((res && res.msg) || '发送失败')
        }
      } catch (error) {
        ElMessage.error('发送失败')
      }
    } else {
      // 直接发送
      messageFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
          try {
            const formData = { ...messageForm, is_draft: 1 }
            const res: any = await homeStore.saveMessageAction(formData)
            if (res && res.code === 0) {
              ElMessage.success('发送成功')
              composeDialogVisible.value = false
              loadMessageList()
            } else {
              ElMessage.error((res && res.msg) || '发送失败')
            }
          } catch (error) {
            ElMessage.error('发送失败')
          }
        }
      })
    }
  }

  // 处理选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedMessages.value = selection
    selectAll.value = selection.length === messageList.value.length && selection.length > 0
  }

  // 全选/取消全选
  const handleSelectAll = (val: boolean) => {
    if (val) {
      // 全选
      messageList.value.forEach((_item: any) => {
        // 这里需要通过element-plus的table方法来选择
      })
    } else {
      // 取消全选
      selectedMessages.value = []
    }
  }

  // 批量操作
  const handleBatchAction = (command: string) => {
    if (selectedMessages.value.length === 0) {
      ElMessage.warning('请先选择要操作的邮件')
      return
    }

    const ids = selectedMessages.value.map((msg: any) => msg.id).join(',')

    switch (command) {
      case 'delete':
        handleDeleteMessages(ids)
        break
      case 'star':
        handleStarMessages(ids)
        break
      case 'unstar':
        handleUnstarMessages(ids)
        break
      case 'recovery':
        handleRecoveryMessages(ids)
        break
      case 'clear':
        handleClearMessages(ids)
        break
    }
  }

  // 删除消息
  const handleDeleteMessages = async (ids: string) => {
    try {
      const res: any = await homeStore.deleteMessageAction({ ids })
      if (res && res.code === 0) {
        ElMessage.success('删除成功')
        loadMessageList()
      } else {
        ElMessage.error((res && res.msg) || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }

  // 标星消息
  const handleStarMessages = async (ids: string) => {
    try {
      const res: any = await homeStore.updateMsgStatusAction({ type: 5, ids })
      if (res && res.code === 0) {
        ElMessage.success('标星成功')
        loadMessageList()
      } else {
        ElMessage.error((res && res.msg) || '标星失败')
      }
    } catch (error) {
      ElMessage.error('标星失败')
    }
  }

  // 取消标星消息
  const handleUnstarMessages = async (ids: string) => {
    try {
      const res: any = await homeStore.updateMsgStatusAction({ type: 6, ids })
      if (res && res.code === 0) {
        ElMessage.success('取消标星成功')
        loadMessageList()
      } else {
        ElMessage.error((res && res.msg) || '取消标星失败')
      }
    } catch (error) {
      ElMessage.error('取消标星失败')
    }
  }

  // 恢复消息
  const handleRecoveryMessages = async (ids: string) => {
    try {
      const res: any = await homeStore.recoveryMessageAction({ ids, table: activeFolder.value })
      if (res && res.code === 0) {
        ElMessage.success('恢复成功')
        loadMessageList()
      } else {
        ElMessage.error((res && res.msg) || '恢复失败')
      }
    } catch (error) {
      ElMessage.error('恢复失败')
    }
  }

  // 彻底删除消息
  const handleClearMessages = async (ids: string) => {
    try {
      const res: any = await homeStore.clearMessageAction({ ids, table: activeFolder.value })
      if (res && res.code === 0) {
        ElMessage.success('彻底删除成功')
        loadMessageList()
      } else {
        ElMessage.error((res && res.msg) || '彻底删除失败')
      }
    } catch (error) {
      ElMessage.error('彻底删除失败')
    }
  }

  // 处理消息操作
  const handleMessageAction = (command: any) => {
    const { action, row } = command
    switch (action) {
      case 'delete':
        handleDeleteMessages(row.id.toString())
        break
      case 'star':
        handleStarMessages(row.id.toString())
        break
      case 'unstar':
        handleUnstarMessages(row.id.toString())
        break
      case 'recovery':
        handleRecoveryMessages(row.id.toString())
        break
      case 'clear':
        handleClearMessages(row.id.toString())
        break
    }
  }

  // 处理上传成功
  const handleUploadSuccess = (_response: any, _file: any, _fileList: any[]) => {
    // 处理上传成功的逻辑
    ElMessage.success('上传成功')
  }

  // 格式化时间
  const formatTime = (timestamp: number) => {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return date.toLocaleString()
  }

  // 分页相关
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    queryForm.page = 1
    loadMessageList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    loadMessageList()
  }

  // 初始化加载
  onMounted(() => {
    loadMessageList()
    loadMessageCount()
    // 模拟加载用户列表
    users.value = [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' },
      { id: 3, name: '王五' },
    ]
  })
</script>

<style scoped>
  .message-container {
    padding: 20px;
  }

  .sidebar-card {
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: column;
  }

  .folder-list {
    flex: 1;
  }

  .folder-item {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    cursor: pointer;
    transition: background-color 0.3s;
    position: relative;
  }

  .folder-item:hover {
    background-color: #f5f5f5;
  }

  .folder-item.active {
    background-color: #ecf5ff;
    color: #409eff;
  }

  .folder-item i {
    margin-right: 10px;
    font-size: 18px;
  }

  .folder-item .el-badge {
    position: absolute;
    right: 20px;
  }

  .compose-btn {
    margin: 20px;
  }

  .message-card {
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: column;
  }

  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .message-toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
